import std/os
import std/strutils

type
  State = enum
    manArgs, page, pageArgs

var state: State = manargs
var pageParts: seq[string] = @[]
var manParts: seq[string] = @[]
var pageArg: string = ""
var section: string = ""

for i, p in commandLineParams():
  if state == manargs and p[0] == '-':
    manParts.add p
  elif state == manargs:
    state = page
    # Sections always begin with a number, but can contain letters after that
    # (e.g 1, 2, 3, 3p, 7ssl, etc). No page title starts with a number, so a
    # a number in the first digit of the first part of the title always
    # specifies a section.
    if p[0].isdigit:
      section = p
      continue

  if state == page and p[0] != '-':
    pageParts.add p
  elif state == page and p[0] == '-':
    state = pageArgs

  if state == pageArgs:
    pageArg = p

if pageArg != "":
  stdout.write "env MANPAGER=\"less +/" & ",\\s*" &
    pageArg & "|^\\s*" & pageArg & "\" "
echo "man " & manParts.join(" ") & " " & section & " " & pageParts.join("-")
